from flask import render_template, redirect, url_for, flash, request
from flask_login import login_required, current_user
from app import db
from app.admin import bp
from app.models import User
from functools import wraps
from sqlalchemy import or_

def admin_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if not current_user.is_authenticated or not current_user.is_admin:
            flash('您没有权限访问此页面。', 'danger')
            return redirect(url_for('main.index'))
        return f(*args, **kwargs)
    return decorated_function

@bp.route('/users')
@login_required
@admin_required
def users():
    # 获取查询参数
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 10, type=int)
    search = request.args.get('search', '')
    status = request.args.get('status', '')
    role = request.args.get('role', '')
    sort = request.args.get('sort', 'created_at')
    order = request.args.get('order', 'desc')

    # 构建查询
    query = User.query

    # 搜索功能
    if search:
        query = query.filter(
            or_(
                User.username.ilike(f'%{search}%'),
                User.email.ilike(f'%{search}%')
            )
        )

    # 状态筛选
    if status == 'active':
        query = query.filter(User.is_active == True)
    elif status == 'inactive':
        query = query.filter(User.is_active == False)

    # 角色筛选
    if role == 'admin':
        query = query.filter(User.is_admin == True)
    elif role == 'user':
        query = query.filter(User.is_admin == False)

    # 排序
    if sort == 'username':
        query = query.order_by(User.username.desc() if order == 'desc' else User.username.asc())
    elif sort == 'email':
        query = query.order_by(User.email.desc() if order == 'desc' else User.email.asc())
    else:  # 默认按创建时间排序
        query = query.order_by(User.created_at.desc() if order == 'desc' else User.created_at.asc())

    # 执行分页查询
    users = query.paginate(page=page, per_page=per_page, error_out=False)

    return render_template('admin/users.html', 
                         title='用户管理',
                         users=users,
                         search=search,
                         status=status,
                         role=role,
                         sort=sort,
                         order=order,
                         per_page=per_page)

@bp.route('/user/<int:id>/toggle_active', methods=['POST'])
@login_required
@admin_required
def toggle_user_active(id):
    user = User.query.get_or_404(id)
    if user == current_user:
        flash('不能修改自己的状态！', 'danger')
    else:
        user.is_active = not user.is_active
        db.session.commit()
        status = '启用' if user.is_active else '禁用'
        flash(f'用户 {user.username} 已{status}', 'success')
    return redirect(url_for('admin.users', **request.args))

@bp.route('/user/<int:id>/delete', methods=['POST'])
@login_required
@admin_required
def delete_user(id):
    user = User.query.get_or_404(id)
    if user == current_user:
        flash('不能删除自己！', 'danger')
    elif user.is_admin:
        flash('不能删除其他管理员！', 'danger')
    else:
        db.session.delete(user)
        db.session.commit()
        flash(f'用户 {user.username} 已删除', 'success')
    return redirect(url_for('admin.users', **request.args)) 